<template>
	<div class="container">
		<a-row :gutter="20" justify="end">
			<a-col :span="2" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/supply/order/pq')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
		<h2 style="text-align:center;margin-bottom: 30px;">查看派遣单详情</h2>

		<a-descriptions title="派遣单信息" style="margin-bottom: 20px;">
			<a-col :span="24" label="项目名称">
				<a-descriptions-item>{{ info.project?.name }}</a-descriptions-item>
			</a-col>
<!--			<a-descriptions-item label="采购单号">{{ info.purchase_order_code }}</a-descriptions-item>-->
			<a-descriptions-item label="派遣单号">{{ info.code }}</a-descriptions-item>
			<a-descriptions-item label="创建时间">{{ info.create_time }}</a-descriptions-item>
			<a-descriptions-item label="送达地址">{{ info.deliver_address }}</a-descriptions-item>
			<a-descriptions-item label="送达时间">{{ info.deliver_time }}</a-descriptions-item>
			<a-descriptions-item label="联系人">{{ info.receiver }}</a-descriptions-item>
			<a-descriptions-item label="联系电话">{{ info.receiver_tel }}</a-descriptions-item>
		</a-descriptions>

		<a-row :gutter="20">
			<a-col :span="24">
				<h3>物资清单</h3>
				<a-table v-if="type==='purchase'" :pagination="false" :data-source="info.materials" :columns="purchaseColumns">
					<template #bodyCell="{ column, index }">
						<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
					</template>
				</a-table>
				<a-table v-if="type==='machineapply'" :pagination="false" :data-source="info.materials" :columns="machineapplyColumns">
					<template #bodyCell="{ column, index }">
						<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
					</template>
				</a-table>

				<a-table v-if="type==='shangtong'" :pagination="false" :data-source="info.SupplyOrderMaterials" :columns="shangtongColumns">
					<template #bodyCell="{ column, index }">
						<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
					</template>
				</a-table>

				<a-table v-if="type==='auxiliary'" :pagination="false" :data-source="info.materials" :columns="auxiliaryColumns">
					<template #bodyCell="{ column, index }">
						<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
					</template>
				</a-table>

				<a-table v-if="type==='a_few_employ'" :pagination="false" :data-source="info.materials" :columns="auxiliaryColumns">
					<template #bodyCell="{ column, index }">
						<template v-if="column.dataIndex === 'id'">{{ index+1 }}</template>
					</template>
				</a-table>


				<!-- <a-form v-if="type=='shangtong' && info.materials">
            <a-row :gutter="20">
              <a-col :span="12">
                <a-form-item label="砼标号（类别）">
                  {{ info.materials[0].model }}
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="预计浇筑方量（m3）">
                  {{ info.materials[0].fangliang }}
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="是否泵送（长度）">
                  {{ info.materials[0].changdu }}
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="申请塌落度（mm）">
                  {{ info.materials[0].luodu }}
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="预计浇筑日期">
                  {{ info.materials[0].add_time }}
                </a-form-item>
              </a-col>
              <a-col :span="24">
                <a-form-item label="备注" name="memo">
                  {{ info.materials[0].memo }}
                </a-form-item>
              </a-col>
            </a-row>
        </a-form>-->
			</a-col>
		</a-row>
		<a-row v-if="realFileList.length" :gutter="24">
			<a-col :span="24" class="py-4 text-right">
				<a-form-item label="发货附件" name="real_pic_path">
					<template v-for="item in realFileList" :key="item.url">
						<a target="_blank" :href="item.url">{{ item.name }}</a><br />
					</template>
				</a-form-item>
			</a-col>
		</a-row>
		<a-row v-if="realPicList.length" :gutter="24">
			<a-col :span="24" class="py-4 text-right">
				<a-form-item label="发货图片" name="real_pic_path"></a-form-item>
			</a-col>
			<a-col v-for="item in realPicList" :key="item.url" :span="6">
				<div class="gallery-image">
					<a-image :width="160" :height="160" :src="item.url" />
				</div>
				<p>{{ item.name }}</p>
			</a-col>
		</a-row>
		<div v-if="shipSplitHistory.length">
			<h1 style="margin-top: 30px;">历史发货记录</h1>
			<a-collapse v-model:activeKey="activeKey">
				<a-collapse-panel v-for="(item, index) in shipSplitHistory" :key="index" :header="'发货单号：' + item.code">
					<h3 style="padding-left:10px;">物资清单</h3>
					<a-table :pagination="false" :data-source="item.materials" :columns="historyColumns" :row-key="(record) => record.key">
					</a-table>
					<h3 style="padding-left:10px;">发货附件</h3>
					<a-row v-if="item.realPicList?.length" :gutter="24">
						<a-col v-for="i in item.realPicList" :key="i.url" :span="6">
							<div class="gallery-image">
								<a-image :width="160" :height="160" :src="item.i" />
							</div>
							<p>{{ item.name }}</p>
						</a-col>
					</a-row>
				</a-collapse-panel>
			</a-collapse>
		</div>
		<a-row :gutter="20">
			<a-col :span="24" class="py-4 text-center">
				<a-space>
					<a-button @click="closeTab('/supply/order/pq')">
						<close-outlined />关闭
					</a-button>
				</a-space>
			</a-col>
		</a-row>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, inject } from "vue";
import { post, listToTree, treeToList } from "../utils";
import { useRoute } from "vue-router";
import { CloseOutlined } from "@ant-design/icons-vue";
import { subtract } from '../utils/operation.js'
const route = useRoute();
const id = computed(() => {
	return route.params.id || 0;
});
import dayjs from "dayjs";
const type = computed(() => {
	return route.query.type;
});
const realFileList = ref([]);
const realPicList = ref([]);
const shipSplitHistory = ref([]);
const activeKey = ref([]);
const purchaseColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return contractOptions.value.filter(item => item.id === text)[0]?.name || "";
		}
	},
	{
		title: "合同余量",
		dataIndex: "contractQuantity",
		align: "center"
	},
	// {
	// 	title: "实际数量",
	// 	dataIndex: "real_quantity",
	// 	align: "center",
	// },
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const machineapplyColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "机械名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "规格型号",
		dataIndex: "model",
		align: "center",
		width: 150
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return contractOptions.value.filter(item => item.id === text)[0]?.name || "";
		}
	},
	{
		title: "合同余量",
		dataIndex: "contractQuantity",
		align: "center"
	},
	// {
	// 	title: "实际数量",
	// 	dataIndex: "real_quantity",
	// 	align: "center",
	// },
	{
		title: "使用时长",
		dataIndex: "use_time",
		align: "center"
	},
	// {
	// 	title: "时长单位",
	// 	dataIndex: "time_unit",
	// 	align: "center",
	// },
	{
		title: "使用时间",
		dataIndex: "use_date",
		align: "center",
		width: 190,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const shangtongColumns = [
	{
		title: "工号",
		dataIndex: ["gonghao", "name"],
		ellipsis: true
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		ellipsis: true
	},
	{
		title: "砼标号（类别）",
		dataIndex: "material",
		customRender: ({ text, record, index, column }) => {
			return text.name + text.model;
		}
	},
	{
		title: "采购方量（m3）",
		dataIndex: "fangliang",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: ["contract", "name"],
		align: "center"
		/*
		customRender: ({ text, record, index, column }) => {
			return contractOptions.value.filter(item => item.id === text)[0]?.name || "";
		}
		*/
	},
	{
		title: "合同余量",
		dataIndex: "remain_quantity",
		align: "center"
	},
	// {
	// 	title: "浇筑方量（m3）",
	// 	dataIndex: "real_quantity",
	// 	align: "center"
	// },
	{
		title: "是否泵送（长度）",
		dataIndex: "changdu",
		align: "center"
	},
	{
		title: "申请塌落度（mm）",
		dataIndex: "luodu",
		align: "center"
	},
	{
		title: "预计浇筑日期",
		dataIndex: "add_time",
		align: "center"
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const auxiliaryColumns = [
	{
		title: "序号",
		dataIndex: "id",
		width: 60,
		align: "center"
	},
	{
		title: "物资名称",
		dataIndex: "name",
		ellipsis: true
	},
	{
		title: "型号规格",
		dataIndex: "model",
		ellipsis: true
	},
	{
		title: "单位",
		dataIndex: "unit",
		align: "center"
	},
	{
		title: "数量",
		dataIndex: "quantity",
		align: "center"
	},
	{
		title: "合同",
		dataIndex: "contract_id",
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return contractOptions.value.filter(item => item.id === text)[0]?.name || "";
		}
	},
	{
		title: "备注",
		dataIndex: "memo",
		align: "center"
	}
];

const historyColumns = computed(() => {
	if (type.value === 'shangtong') {
		return [{
			title: "工号",
			dataIndex: 'use_position',
			ellipsis: true
		},
		{
			title: "预计浇筑部位",
			dataIndex: "SupplyOrderMaterial",
			ellipsis: true,
			customRender: ({ text, record, index, column }) => {
				return text.expected_location;
			}
		},
		{
			title: "砼标号（类别）",
			dataIndex: "model",
			customRender: ({ text, record, index, column }) => {
				return record.name + text;
			}
		},
		{
			title: "采购方量（m3）",
			dataIndex: "SupplyOrderMaterial",
			customRender: ({ text, record, index, column }) => {
				return text.fangliang;
			}
		},
		{
			title: "浇筑方量（m3）",
			dataIndex: "SupplyOrderMaterial",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text.real_quantity;
			}
		}]
	}
	return [
		{
			title: "物资名称",
			dataIndex: "name",
			ellipsis: true,
			customRender: ({ text, record, index, column }) => {
				return text;
			}
		},
		{
			title: "型号规格",
			dataIndex: "model",
			ellipsis: true,
			customRender: ({ text, record, index, column }) => {
				return text;
			}
		},
		{
			title: "单位",
			dataIndex: "unit",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text;
			}
		},
		{
			title: "采购数量",
			dataIndex: "SupplyOrderMaterial",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text.quantity;
			}
		},
		{
			title: "发货数量",
			dataIndex: "SupplyOrderMaterial",
			align: "center",
			customRender: ({ text, record, index, column }) => {
				return text.real_quantity;
			}
		}
	]
})

const info = ref({});
const contractOptions = ref([]);
onMounted(() => {
	post(`supplyOrder/info`, { id: id.value }).then(async data => {
		data.real_pic_path = JSON.parse(data.real_pic_path || "[]");
		for (const file of data.real_pic_path) {
			const suffix = file.url.split(".").pop();
			if (['jpg', 'jpeg', 'png'].includes(suffix)) {
				realPicList.value.push(file)
			} else {
				realFileList.value.push(file);
			}
		}
		if (type.value === "shangtong") {
			/*
			const departmentTree = await post("department/getTrees", { type: 4, parent_id: data.project_id });
			const departmentList = treeToList(departmentTree, []);
			const info = data.materials[0]?.SupplyOrderMaterial || {}
			const gonghao = departmentList.filter((item) => {
				return item.id === info.gonghao_id
			})[0]?.name;
			const part = departmentList.filter((item) => {
				return item.id === info.position
			})[0]?.name;
			data.materials.map((item) => {
				item.use_position = ((gonghao || '') + (part || ''));
				return item;
			});
			*/
		}

		// 补充合同余量
		let contractIds = [];
		contractIds = contractIds.concat(data.materials.map(item => item.SupplyOrderMaterial.contract_id).filter(item => !!item));
		let supplyOrderMaterialInfos = [];
		let contractList = [];
		if (contractIds.length > 0) {
			contractList = await post("contract/all", { contract_ids: contractIds.join(",") });
			contractOptions.value = contractList;
			const materialIds = data.materials.map(item => item.id);
			supplyOrderMaterialInfos = await post(`supplyOrder/materials`, {
				contract_ids: JSON.stringify(contractIds),
				material_ids: JSON.stringify(materialIds)
			});
		}

		data.materials = data.materials.map(item => {
			const { quantity, real_quantity, supplier_id, unit, memo, use_date, use_time, time_unit, fangliang, expected_location, luodu, changdu, add_time, part, contract_id } = item.SupplyOrderMaterial;
			// 验收总数
			const ysQuantitySum = supplyOrderMaterialInfos
				.filter(i => {
					return i.contract_id === contract_id && i.material_id === item.id && i.ys_quantity > 0;
				})
				.reduce((target, item) => {
					return target + parseFloat(item.ys_quantity);
				}, 0);
			const contractMaterial = contractList
				.filter(i => i.id === contract_id)
				.map(i => {
					return i.materials.filter(j => j.id === item.id)[0];
				})[0];
			const contractQuantity = subtract([(contractMaterial?.ContractMaterial.quantity || 0), ysQuantitySum]);
			return {
				...item,
				quantity,
				real_quantity,
				unit,
				memo,
				use_date: dayjs(use_date).format("YYYY-MM-DD HH:mm:ss"),
				use_time,
				time_unit,
				supplier_id,
				fangliang,
				luodu,
				changdu,
				part,
				contractQuantity,
				contract_id,
				add_time: dayjs(add_time).format("YYYY-MM-DD HH:mm:ss"),
				expected_location
			};
		});
		data.create_time = dayjs(data.create_time).format("YYYY-MM-DD HH:mm:ss");
		data.deliver_time = dayjs(data.deliver_time).format("YYYY-MM-DD HH:mm:ss");
		info.value = data;
		shipSplitHistory.value = (await post("supplyOrder", { purchase_order_code: info.value.purchase_order_code, ship_status: 2 })).data.filter(item => item.id !== parseInt(id.value));
		shipSplitHistory.value.map(item => {
			item.realPicList = JSON.parse(item.real_pic_path || "[]");
			return item;
		})
		if (type.value === 'shangtong' && shipSplitHistory.value.length) {
			const departmentTree = await post("department/getTrees", { type: 4, parent_id: data.project_id });
			const departmentList = treeToList(departmentTree, []);
			for (const item of shipSplitHistory.value) {
				const info = item.materials[0]?.SupplyOrderMaterial || {}
				const gonghao = departmentList.filter((item) => {
					return item.id === info.gonghao_id
				})[0]?.name;
				const part = departmentList.filter((item) => {
					return item.id === info.position
				})[0]?.name;
				item.materials.map((i) => {
					i.use_position = ((gonghao || '') + (part || ''));
					return i;
				});
			}
		}
	});
});

const closeTab = inject("closeTab");
</script>

<style scoped lang="scss">
.container {
	background: #fff;
	padding: 20px;
  :deep(.ant-collapse-content-box) {
    padding: 0px;
  }
}
</style>
